package com.ctgu.fastleader.utility;

import java.io.FileInputStream;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelImport {

    //导入Excel数据

    public List<Map> importExcelAction(String filePath) throws Exception {

//文件路径

        XSSFWorkbook wookbook = new XSSFWorkbook(new FileInputStream(filePath));

        XSSFSheet sheet = wookbook.getSheet("Sheet1");

        //获取到Excel文件中的所有行数

        int rows = sheet.getPhysicalNumberOfRows();

        //遍历行

        List<Map> list = new ArrayList<>();

        for (int i = 0; i < rows; i++) {

            // 读取左上端单元格

            XSSFRow row = sheet.getRow(i);

            // 行不为空

            if (row != null) {

                Map map = new HashMap();

                //获取到Excel文件中的所有的列

                int cells = row.getPhysicalNumberOfCells();

                //id

                XSSFCell goodsid = row.getCell(0);

                String id = getValue(goodsid);

                //name

                XSSFCell goodsname = row.getCell(1);

                String name = getValue(goodsname);

                //price

                XSSFCell goodsprice = row.getCell(2);

                String price = getValue(goodsprice);

                //info

                XSSFCell goodsinfo = row.getCell(3);
                String info = getValue(goodsinfo);


                map.put("id", id);

                map.put("name", name);

                map.put("price", price);

                map.put("info", info);

                list.add(map);

            }

        }
        return list;

    }

    private String getValue(XSSFCell xSSFCell) {

        if (null == xSSFCell) {

            return "";

        }

        if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_BOOLEAN) {

            // 返回布尔类型的值

            return String.valueOf(xSSFCell.getBooleanCellValue());

        } else if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_NUMERIC) {

            // 返回数值类型的值

            return String.valueOf(xSSFCell.getNumericCellValue());

        } else {

            // 返回字符串类型的值

            return String.valueOf(xSSFCell.getStringCellValue());

        }

    }
}
